﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Business;
using Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;
using iTextSharp.text.xml;
using iTextSharp.text.html;
using DataAccess;
//using System.Windows.Forms;

public partial class admin_View_VAreport : @base {
    private PdfWriter writer;
    private ArrayList title = new ArrayList(3);
    private ArrayList infor = new ArrayList(16);
    private Paragraph pa;
    int selectedClient_id;
    int dateIndex;


    private class headerfooter {
        private PdfPTable head;
        private PdfPTable foot;
        private iTextSharp.text.Image _img;
        private Font font;
        private String t1 = "i2iTechnologies PO Box 1192, Clevand Qld 4163, Australia";
        private String t2 = "Office (07) 3829 1235 Fax (07) 3829 1238 Mob: 0439 717 244 Web: www.i2i-technologies.com.au ";
        private String t3 = "@i2iTechnologies";

        public headerfooter() {
            head = new PdfPTable(1);
            foot = new PdfPTable(1);
            font = new Font();
            font.Color = BaseColor.BLUE;
            font.Size = 6f;
            font.SetFamily("Arial");
        }
        public PdfPTable Head {
            get { return head; }

        }
        public PdfPTable Foot {
            get { return foot; }

        }

        public void setHeader(String path, float width, int align, int border, int scale) {
            PdfPTable header = new PdfPTable(1);
            header.TotalWidth = width - 35;
            _img = iTextSharp.text.Image.GetInstance(path);
            _img.ScalePercent(scale);
            PdfPCell c = new PdfPCell(_img, false);

            c.HorizontalAlignment = align;
            c.Border = border;
            header.AddCell(c);
            head = header;

        }
        public void setFooter(float width) {

            PdfPTable footer = new PdfPTable(1);
            footer.TotalWidth = width;
            Chunk ck = new Chunk(t1, font);
            Phrase p1 = new Phrase(ck);

            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_CENTER;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_MIDDLE;

            fc.Rowspan = 1;
            footer.AddCell(fc);

            ck = new Chunk(t2, font);
            fc.Phrase = new Phrase(ck);
            fc.Rowspan = 1;
            footer.AddCell(fc);

            fc.Rowspan = 1;

            ck = new Chunk(t3, font);
            fc.Phrase = new Phrase(ck);
            footer.AddCell(fc);

            foot = footer;

        }
    }

    private class _events : PdfPageEventHelper {
        // private iTextSharp.text.Image _img;
        private String path;



        public _events(String p) {
            /*
            * create single instance so image bytes added **ONCE** to the PDF file,
            * instead of every time you start a new page
            */

            path = p + "/logo.png";
            //     _img = iTextSharp.text.Image.GetInstance(path + "/logo.png");

            /*
            * scale image to fit available space, if needed
            */
            //  _img.ScalePercent(50);
        }
        public override void OnEndPage(PdfWriter writer, Document document) {
            Rectangle page = document.PageSize;

            headerfooter hfPage = new headerfooter();

            hfPage.setHeader(path, page.Width - 35, Element.ALIGN_RIGHT, Rectangle.NO_BORDER, 100);
            hfPage.setFooter(page.Width);
            PdfPTable head = hfPage.Head;
            PdfPTable foot = hfPage.Foot;


            /*
            * write header w/WriteSelectedRows(); requires absolute positions!
            */
            head.WriteSelectedRows(
               0, -1,          // first/last row; -1 flags all write all rows
               0, // left offset
                // ** bottom** yPos of the table
                // page.Height - document.TopMargin + head.TotalHeight,
              820,
               writer.DirectContent
             );


            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
        }
    }// end of Thao code


    protected void Page_Load(object sender, EventArgs e) {
        DataTable Clients = new DataTable();
        ReportServices report = new ReportServices();

        if (!IsPostBack) {
            // client = ClientDetails;
            if (ClientDetails != null) {
                int parentClientID = ClientDetails.ParentClientID;
                if (parentClientID == 0) {
                    Clients = report.getClientsByParent(ClientDetails.ClientID);
                    if (Clients.Rows.Count == 0) {
                        Clients.Rows.Add(ClientDetails.ClientName, ClientDetails.ClientID);
                    }
                } else {
                    Clients.Columns.Add("clientName", typeof(string));
                    Clients.Columns.Add("client_id", typeof(int));
                    Clients.Rows.Add(ClientDetails.ClientName, ClientDetails.ClientID);
                    //    selectedClient = ClientDetails.ClientID;
                }
                int ok = 1;
                foreach (DataRow cl in Clients.Rows) {
                    String clientName = cl["clientName"].ToString();
                    String clientid = cl["client_id"].ToString();
                    System.Web.UI.WebControls.ListItem clientitem = new System.Web.UI.WebControls.ListItem(clientName, clientid, true);
                    DropDownClientList.Items.Add(clientitem);
                    if (ok == 1) {
                        DropDownClientList.SelectedValue = clientid;
                        ok = 0;
                        selectedClient_id = ToInt(clientid);
                    }
                }
                // selectedClient = ToInt(DropDownClientList.SelectedValue);
            } else {
                string jscript = "<script language='javascript'  type='text/javascript'> parent.document.location.href= '../Default.aspx'</script>";
                //Page.RegisterClientScriptBlock("key2ClientBlock", jscript);
                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "key3ClientBlock", jscript);
            }

        }


    }
    protected PdfPTable setLegendTable(float width) {
        ReportServices report = new ReportServices();
        PdfPTable legendTable = new PdfPTable(2);
        // legendTable.TotalWidth = width+30;
        legendTable.SetTotalWidth(new float[] { 25, 170 });
        legendTable.WidthPercentage = 85;
        DataTable statusTable = new DataTable();
        statusTable = report.getSeverity();
        Phrase title = new Phrase("");
        PdfPCell c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        title = new Phrase("LEGEND", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));
        c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        foreach (DataRow r in statusTable.Rows) {
            string statusName = r["statusName"].ToString();
            string statusDes = r["statusDescription"].ToString();
            int status_id = ToInt(r["status_id"].ToString());
            Phrase p1 = new Phrase(statusName, getFont(getColor(status_id), 8, "Arial"));
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_JUSTIFIED;

            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_MIDDLE;
            legendTable.AddCell(fc);
            p1 = new Phrase(statusDes, getFont(BaseColor.BLACK, 8, "Arial"));
            fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            legendTable.AddCell(fc);
        }

        return legendTable;
    }
    protected PdfPTable setTitleTable(ArrayList title, float width) {
        PdfPTable titleTable = new PdfPTable(1);
        //titleTable.SetTotalWidth(new float[] {5 });
        titleTable.WidthPercentage = 82;

        Chunk ck;


        Font font1; Phrase p1 = new Phrase();
        // titleTable.TotalWidth = width-80;
        for (int i = 0; i < title.Count; i++) {
            if (i + 1 == title.Count)
                font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 13);
            else
                font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 15);
            ck = new Chunk(title[i].ToString(), font1);


            p1.Add(ck);
            p1.Add(Chunk.NEWLINE);
            p1.Add(Chunk.NEWLINE);
        }
        PdfPCell fc = new PdfPCell(p1);
        fc.HorizontalAlignment = Element.ALIGN_CENTER;
        fc.VerticalAlignment = Element.ALIGN_MIDDLE;
        fc.MinimumHeight = 0f;
        fc.Border = Rectangle.NO_BORDER;
        fc.VerticalAlignment = Element.ALIGN_LEFT;
        fc.MinimumHeight = 0;
        fc.PaddingBottom = 0.1f;
        fc.PaddingTop = 0.1f;
        //fc.Leading=15f;
        titleTable.AddCell(fc);


        return titleTable;
    }
    //create table of information for the first page
    protected PdfPTable setTableInfo(ArrayList info, float width) {
        PdfPTable tableInfo = new PdfPTable(2);
        Chunk ck;
        Font font1;
        tableInfo.TotalWidth = width;
        for (int i = 0; i < 16; i++) {
            Phrase p1 = new Phrase();
            switch (i) {
                case 0:
                case 2:
                case 4:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 1:
                case 3:
                case 5:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 11);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 13:
                case 15:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10.5f);
                    String address = info[i].ToString();
                    String t;
                    int index = 0;
                    int count = 0;
                    while (true) {
                        count = address.IndexOf(';', index);
                        if (count == -1) {
                            ck = new Chunk(address.Substring(index).Trim(), font1);
                            p1.Add(ck);
                            break;
                        }
                        t = address.Substring(index, count - index).Trim();
                        index = count + 1;
                        ck = new Chunk(t, font1);
                        p1.Add(ck);
                        p1.Add(Chunk.NEWLINE);

                    }
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 12:
                case 14:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                default:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 9.5f);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
            }
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.MinimumHeight = 0f;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            if ((i > 5) && (i < 10)) {
                // fc.SetLeading(0, 1.0f);
                fc.FixedHeight = 13;

            } else
                fc.MinimumHeight = 0;
            fc.PaddingBottom = 0.1f;
            fc.PaddingTop = 0.1f;
            tableInfo.AddCell(fc);
        }
        return tableInfo;

    }
    protected Font getFont(BaseColor color, float size, string type) {
        Font font = new Font();
        font.Color = color;//BaseColor.BLUE;
        font.Size = size;// 6f;
        font.SetFamily(type);//"Arial");
        return font;
    }
    protected void Severity_changed(object sender, EventArgs e) {
        DataTable severity = new DataTable();
        if (SelectSeverity_DropDownList.SelectedValue == "Choose Severity") {
            //if (changeSeverity == false)
            //{
            ReportServices rs = new ReportServices();
            // ds = rs.getOptions(CLIENTID);
            // severity= ds.Tables[0];
            severity = rs.getSeverity();
            //changeSeverity = true;
            //}
            foreach (DataRow status in severity.Rows) {
                String statusName = status["statusName"].ToString();
                string statusID = status["status_id"].ToString();

                System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(statusName, statusID, true);
                SeverityCheckBoxList.Items.Add(ls);
            }

        } else {
            SeverityCheckBoxList.Items.Clear();
        }



    }
    protected DataTable getSelectedSites() {
        DataTable Sites = new DataTable();
        DataTable selectedSites = new DataTable();
        selectedSites.Columns.Add("siteName", typeof(string));
        selectedSites.Columns.Add("site_id", typeof(int));
        if (SelectSite_DropDownList1.SelectedValue == "Choose Sites") {

            foreach (System.Web.UI.WebControls.ListItem lt in SitesCheckBoxList.Items) {

                if (lt.Selected) {
                    string siteName = "";
                    siteName = lt.Text;
                    int siteID = Int32.Parse(lt.Value);
                    selectedSites.Rows.Add(siteName, siteID);
                }
            }
        } else {
            //if (changeSite == false)
            //{
            ReportServices rs = new ReportServices();

            Sites = rs.getSiteByCLientID(selectedClient_id);
            //changeSite = true;
            //}
            selectedSites = Sites;

        }
        return selectedSites;
    }
    protected DataTable getSelectedStatus() {
        DataTable severity = new DataTable();
        DataTable selectedStatus = new DataTable();
        selectedStatus.Columns.Add("statusName", typeof(string));
        selectedStatus.Columns.Add("status_id", typeof(int));
        if (SelectSeverity_DropDownList.SelectedValue == "Choose Severity") {

            foreach (System.Web.UI.WebControls.ListItem lt in SeverityCheckBoxList.Items) {

                if (lt.Selected) {
                    string statusName = "";
                    statusName = lt.Text;
                    int statusID = Int32.Parse(lt.Value);
                    selectedStatus.Rows.Add(statusName, statusID);
                }
            }
        } else {
            //if (changeSeverity == false)
            //{
            ReportServices rs = new ReportServices();
            severity = rs.getSeverity();
            //    changeSeverity = true;
            //}
            selectedStatus = severity;

        }
        return selectedStatus;
    }


    protected void Client_Changed(object sender, EventArgs e) {
        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        SelectSite_DropDownList1.Text = "Any";
        SelectSite_DropDownList1.SelectedIndex = 0;
        SitesCheckBoxList.Items.Clear();
        //changeSite = false;
    }
    protected string getShortName(string name) {
        string name1 = name.Trim();
        //int length = name.Length;
        string shorname = "";
        int ix = 0;
        shorname = shorname + name.Substring(0, 1).ToString().ToUpper();
        name1 = name.Substring(1);
        int index = index = name1.IndexOf(" ", ix);
        while (index != -1) {

            name1 = name1.Substring(index).Trim();
            shorname = shorname + name1.Substring(0, 1);
            index = name1.IndexOf(" ", ix);
        }
        return shorname;
    }
    protected void Site_changed(object sender, EventArgs e) {
        DataTable Sites = new DataTable();
        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        if (SelectSite_DropDownList1.SelectedValue == "Choose Sites") {
            //if (changeSite == false)
            //{
            ReportServices rs = new ReportServices();
            Sites = rs.getSiteByCLientID(selectedClient_id);
            //changeSite = true;
            //}
            foreach (DataRow site in Sites.Rows) {
                String siteName = site["siteName"].ToString();
                string siteID = site["site_id"].ToString();

                System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(siteName, siteID, true);
                SitesCheckBoxList.Items.Add(ls);
            }

        } else {
            SitesCheckBoxList.Items.Clear();
        }



    }
    protected BaseColor getColor(int status_id) {
        switch (status_id) {
            case 1: return BaseColor.GREEN;
            case 2: return BaseColor.YELLOW;
            case 3: return BaseColor.ORANGE;
            case 4: return BaseColor.RED;
            case 5: return BaseColor.BLUE;
            default: return BaseColor.BLACK;
        };


    }
    protected Paragraph getFirstPage() {
        Paragraph pr = new Paragraph();
        //pr.Font=getFont(BaseColor.BLACK,
        pr.Add(new Chunk("Vibration Survey & Report", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 18)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Vibration Monitoring", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Vibration analysis is a predictive maintenance method, which allows for early problem identification in active machines and is the most effective machine condition monitoring technique. Early detection of gear tooth wear, bearing deterioration, shaft misalignment, structural looseness, imbalance, cavitation, and all other correctable problems allows planned adjustment and repairs to equipment. This avoids costly breakdown repairs and disruption to operations. I2i uses latest tri-axial technology to collect data from all three planes simultaneously. This makes our machine assessment reports not only more accurate than our competitors but also allows for faster data acquisition and greater access to your plant and equipment from a single point location.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Survey and Data Collection", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("An i2i engineer will visit your site to carryout a survey and collect data and samples as required at the pre-arranged time. A preliminary analysis report of any significant defects found and course of action will be printed and made available for discussion before the engineer leaves the site.  Site time may vary depending on how long it takes to survey the equipment due to its operational availability including both vehicular and safe plant access", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Analysis and Reporting", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Once collected, the data is analysed by our trained engineers and a preliminary report is generated that identifies any OUT of LIMIT equipment faults and problem rectification while our engineers are still on site.  The data is then transferred to our Brisbane office for further analysis. This includes various techniques such as Narrow Band Alarms, RMS trends; Crest Factor (intensity), Statistical Process Control, Phase Relationship and Demodulation are used in every reading to assist the analysis. ", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("The report lists all the client’s machines (any un-surveyed are still listed, but Machine un-surveyed is entered under that machine). For each machine, the report details any problems found and their severity, as well as any recommended corrective actions.  A full report is then emailed within (3) Three days in PDF format, with a bound hard copy posted out to the client or client’s representative.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Equipment", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("DLI Engineering DCX XRT PC based portable Four Channel data collection unit and analyser, serial number 556; DLI Engineering accelerometer, model N0 9938-7-NC-DLI serial number S/N 1223", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("General Layout of each page", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        Chunk chunk = new Chunk("A numbered list of equipment is generally shown on each page. The “equipment”, “component” and “criticality level” is detailed and colour coded next to each component surveyed. The headings can include descriptions requested by the client, or in the absence of this a convenient designation is made by the analyst.  A reference filename is also given for the report stored on the i2i computer system for future reference if required.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10));
        pr.Add(chunk);
        pr.Alignment = Element.ALIGN_JUSTIFIED;
        pr.SpacingAfter = 0;
        pr.SpacingBefore = 0;
        pr.Leading = 13;
        return pr;

    }
    protected string getSitesTitle(DataTable sites) {
        string sitesTitle = "";
        int num = sites.Rows.Count;
        int i = 0;

        foreach (DataRow s in sites.Rows) {
            sitesTitle = sitesTitle + s["siteName"].ToString();
            i++;
            if (i + 1 == num)
                sitesTitle = sitesTitle + " & ";
            else

                if (i != num)
                    sitesTitle = sitesTitle + ", ";

        }
        return sitesTitle;
    }

    protected void FullReport(object sender, EventArgs e) {
        string selectedDate = "";
        Client selectedClient = new Client();
        Document document = new Document(PageSize.A4, 110, 95, 60, 125);
        headerfooter hf = new headerfooter();
        UserServices us = new UserServices();
        string ClientParentName = "";
        System.DateTime str_date = new System.DateTime();

        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        dateIndex = 0;
        selectedClient = us.getClientByID(selectedClient_id);

        string selectedClientName = selectedClient.ClientName;

        try {
            //selectedDate = DropDownListDate.SelectedValue.Substring(0, DropDownListDate.SelectedValue.IndexOf(" ")).Trim();
            //str_date = DateTime.Parse(selectedDate, System.Globalization.CultureInfo.CreateSpecificCulture("en-AU").DateTimeFormat);
            selectedDate = DropDownListDate.SelectedValue;

            dateIndex = DropDownListDate.SelectedIndex + 1;//Request.QueryString["selectedDate"].ToString();

        } catch (Exception ex) {
            Console.Write(ex);
            // MessageBox.Show("No report available");

        }
        // step 2: we create a writer that listens to the document
        String path1 = Server.MapPath("Report");
        String p = Server.MapPath("Images");

        String path = path1 + "/Template.pdf";


        int ok = 0;
        while (ok != -1) {

            try {

                writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
                ok = -1;
            } catch (Exception exception) {
                ok++;
                path = path1 + "/Template" + ok.ToString() + ".pdf";
            }
        }


        Rectangle page = document.PageSize;
        // document.SetMargins(120, 90, 83, 30);
        document.SetMargins(120, 20, 60, 125);

        hf.setHeader(p + "/logoi2i.png", page.Width + 35, Element.ALIGN_CENTER, Rectangle.NO_BORDER, 75);
        hf.setFooter(page.Width);

        PdfPTable head = hf.Head;
        PdfPTable foot = hf.Foot;
        DataTable selectedSites = new DataTable();
        DataTable selectedStatus = new DataTable();
        selectedSites.Columns.Add("siteName", typeof(string));
        selectedSites.Columns.Add("site_id", typeof(int));
        selectedStatus.Columns.Add("statusName", typeof(string));
        selectedStatus.Columns.Add("status_id", typeof(int));

        try {



            selectedSites = getSelectedSites();

            selectedStatus = getSelectedStatus();

            document.Open();

            //Add for test

            // Phrase content = new Phrase("dfdf",getFont(BaseColor.BLACK, 16f, "Arial"));
            //    Paragraph contentPa = new Paragraph(content);
            //    contentPa.Leading = 10;
            ////   // contentPa.Font = 
            //    contentPa.Alignment = Element.ALIGN_CENTER;
            //    document.Add(contentPa);
            //    string fileName = "ddd";
            //Add for test


            //Testserver


            // Add header for first page
            head.WriteSelectedRows(0, -1, 0, 820, writer.DirectContent);
            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
            string tt = "";
            if (ClientDetails.ParentClientID != 0) {
                ClientParentName = "" + us.getClientByID(ClientDetails.ParentClientID).ClientName;
                tt = ClientParentName + " (" + selectedClientName + ")";
            } else
                //ClientParentName = ClientDetails.ClientName;
                tt = selectedClientName;
            //title.Add(ClientParentName + " (" + selectedClientName + ")"); // + " Sites";
            title.Add(tt);
            /* no need to add title

          //string sitesTitle = getSitesTitle(selectedSites);

          //  title.Add(sitesTitle);*/
            title.Add("Vibration Inspection and Survey Report");
            title.Add(selectedDate);
            PdfPTable TitleTable = new PdfPTable(1);
            TitleTable = setTitleTable(title, page.Width);


            for (int i = 0; i < 2; i++) {
                Phrase t = new Phrase("");
                pa = new Paragraph(t);
                if (i == 0)
                    pa.Leading = 110;
                else
                    pa.Leading = 20;
                pa.Alignment = Element.ALIGN_CENTER;
                document.Add(pa);


            }
            TitleTable.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(TitleTable);
            // string fileName = "" + selectedClient.ClientID + "-VA-" + getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";
            string fileName = "";
            if (selectedClient.ParentClientID != 0)
                fileName = "" + selectedClient.ParentClientID + "-VA-" + getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";
            else
                fileName = "" + selectedClient.ClientID + "-VA-" + getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";

            PdfPTable information = new PdfPTable(2);
            infor.Add("Engineer");
            infor.Add("Paul Clibbon");
            infor.Add("Report Filename");
            infor.Add(fileName);
            infor.Add("Report Distribution");
            infor.Add(selectedClient.ContactPerson);
            infor.Add("Phone");
            infor.Add(selectedClient.PhoneMobile.ToString());
            infor.Add("Fax");
            infor.Add(selectedClient.Fax.ToString());
            infor.Add("Email");
            infor.Add(selectedClient.Email);
            infor.Add("Address");
            infor.Add(selectedClient.Address);
            infor.Add("Report Distribution: Email reports in PDF format to:  ");
            infor.Add(selectedClient.DistributedEmail);
            information = setTableInfo(infor, page.Width - 80);
            information.HorizontalAlignment = Element.ALIGN_CENTER;
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(information);
            /* PdfPTable legend = new PdfPTable(2);
             legend = setLegendTable(page.Width);
             legend.HorizontalAlignment = Element.ALIGN_LEFT;
             document.Add(legend);           */



            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            // document.Add(information);
            PdfPTable legend = new PdfPTable(2);
            legend = setLegendTable(page.Width);
            legend.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(legend);

            // set event automatically generate header for all next pages
            _events ev = new _events(p);
            writer.PageEvent = ev;
            // add new page
            document.SetMargins(120, 76, 83, 125);
            document.NewPage();

            //set first page 
            Paragraph firstPage = getFirstPage();
            document.Add(firstPage);

            // TEST SERVER START



            document.NewPage();
            DataTable MachinesOfSites = new DataTable();
            ReportServices r = new ReportServices();
            MachinesOfSites = r.getMachineOfSites(selectedSites);
            DataTable componentsOfSites = new DataTable();
            componentsOfSites = r.getComponentsByMachinesAndStatusByDate(MachinesOfSites, selectedStatus, selectedDate);// str_date);
            int num = componentsOfSites.Rows.Count;
            int index = 0;
            int listCount = 1;
            foreach (DataRow site in selectedSites.Rows) {
                String siteName = site["siteName"].ToString();
                string siteID = site["site_id"].ToString();
                bool haveValue = false;
                Phrase content = new Phrase(siteName, getFont(BaseColor.BLACK, 16f, "Arial"));
                Paragraph contentPa = new Paragraph(content);
                contentPa.Leading = 10;
                // contentPa.Font = 
                contentPa.Alignment = Element.ALIGN_CENTER;
                document.Add(contentPa);
                index++;
                int count = 0;
                string machineType = "";

                DataRow[] machinesOfSite = MachinesOfSites.Select("site_id = " + siteID.Trim(), "MachineType_id ASC");

                if (machinesOfSite.Length == 0) {
                    string noValue = " No component met the search criteria!";
                    content = new Phrase(noValue, getFont(BaseColor.BLACK, 12f, "Arial"));
                    contentPa = new Paragraph(content);
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(contentPa);
                    continue;
                }
                List componentList = new List(List.ORDERED);
                bool firstMachine = true;
                foreach (DataRow row in machinesOfSite) {
                    string machine_id = row["Machine_id"].ToString();
                    string ma_id = row["machine_id"].ToString();
                    DataRow[] componentsOfMachine = componentsOfSites.Select("machine_id= " + machine_id.Trim(), "component_id ASC");
                    if (componentsOfMachine.Length == 0)
                        continue;
                    //add machine type
                    haveValue = true;
                    if (machineType != row["MachineType_name"].ToString()) {
                        if (firstMachine == false) {
                            content = new Phrase(machineType, getFont(BaseColor.BLUE, 14f, "Arial"));
                            contentPa = new Paragraph(content);
                            contentPa.Alignment = Element.ALIGN_CENTER;
                            document.Add(Chunk.NEWLINE);
                            document.Add(contentPa);
                            document.Add(Chunk.NEWLINE);
                            document.Add(componentList);
                        }
                        machineType = row["MachineType_name"].ToString();
                        count++;
                        componentList = new List(List.ORDERED);
                        componentList.First = listCount;
                        firstMachine = false;
                    }
                    // name of machine

                    string stt = "";
                    string fname = "";
                    string componentName = "";
                    string component_id = "0";
                    string comment = "";
                    // get components of machine
                    bool first = true;
                    string machineName = "";
                    Phrase statusName = new Phrase("");

                    foreach (DataRow component in componentsOfMachine) {

                        if (component_id != component["component_id"].ToString()) {
                            if (first != true) {

                                iTextSharp.text.ListItem item =
                                   new iTextSharp.text.ListItem("" + machineName + "-" + componentName + " ", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));

                                // content = new Phrase(" "+fname,getFont(BaseColor.RED,12,"Arial"));
                                item.Add(statusName);//,getFont(BaseColor.RED,12,"Arial"));
                                item.Add(Chunk.NEWLINE);
                                content = new Phrase(comment, new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 11));//getFont(BaseColor.BLACK,11,"Arial"));
                                contentPa = new Paragraph(content);
                                contentPa.Alignment = Element.ALIGN_JUSTIFIED;
                                item.Add(contentPa);
                                item.Add(Chunk.NEWLINE);

                                componentList.Add(item);
                                listCount++;
                                fname = "";
                                statusName = new Phrase("");


                            }
                            component_id = component["component_id"].ToString();
                            machineName = row["MachineName"].ToString();
                            componentName = component["componentName"].ToString();

                            comment = component["comments"].ToString();
                            fname = component["faultName"].ToString();
                            stt = component["status_id"].ToString();
                            Chunk c = new Chunk(fname, getFont(getColor(ToInt(stt)), 12, "Arial"));
                            statusName = new Phrase("");
                            statusName.Add(c);
                            first = false;

                        } else {
                            if (fname != "") {
                                Chunk c = new Chunk("/", getFont(BaseColor.BLACK, 12, "Arial"));
                                statusName.Add(c);
                            }
                            // fname=fname+component["faultName"].ToString();
                            fname = component["faultName"].ToString();
                            stt = component["status_id"].ToString();
                            Chunk c1 = new Chunk(fname, getFont(getColor(ToInt(stt)), 12, "Arial"));
                            statusName.Add(c1);
                        }

                    }
                    iTextSharp.text.ListItem item1 =
                                   new iTextSharp.text.ListItem("" + machineName + "-" + componentName + " ", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));
                    //content = new Phrase(" " + fname, getFont(BaseColor.RED, 12, "Arial"));
                    item1.Add(statusName);//,getFont(BaseColor.RED,12,"Arial"));
                    item1.Add(Chunk.NEWLINE);
                    content = new Phrase(comment, new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 11));//getFont(BaseColor.BLACK, 11, "Arial"));
                    contentPa = new Paragraph(content);
                    contentPa.Alignment = Element.ALIGN_JUSTIFIED;
                    item1.Add(contentPa);
                    item1.Add(Chunk.NEWLINE);

                    componentList.Add(item1);
                    listCount++;
                    statusName = new Phrase("");
                    fname = "";
                }
                content = new Phrase(machineType, getFont(BaseColor.BLUE, 14f, "Arial"));
                contentPa = new Paragraph(content);
                contentPa.Alignment = Element.ALIGN_CENTER;
                document.Add(Chunk.NEWLINE);
                document.Add(contentPa);
                document.Add(Chunk.NEWLINE);
                document.Add(componentList);
                if (haveValue == false) {
                    string noValue = " No component met the search criteria!";
                    content = new Phrase(noValue, getFont(BaseColor.BLACK, 12f, "Arial"));
                    contentPa = new Paragraph(content);
                    contentPa.Alignment = Element.ALIGN_CENTER;
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(contentPa);
                }
                document.NewPage();

            }

            //TEST SERVER END
            document.Close();

            // set name for attact file


            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/pdf";
            Response.WriteFile(path);
            Response.Flush();
            Response.End();
            Response.Clear();

        } catch (Exception ee) {
            Console.Error.WriteLine(ee.StackTrace);
            Console.Error.WriteLine(ee.Message);

            if (ee.InnerException != ee) {

                // Console.Error.WriteLine(ee.InnerException.Message);
            }
        }



        // End of Thao



    }
}
